package com.commerceE.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.domain.Category;
import com.commerceE.domain.Products;
import com.commerceE.domain.User;
import com.commerceE.service.CategoryService;
import com.commerceE.service.ProductService;

/**
 * Sample controller for going to the home page with a message
 */
@SessionAttributes({"currentUser","userSecurityContext"})
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ProductService productService;
	
	@ModelAttribute("currentUser")
	public User initCurrentUser(Model model) {
		Object user = RequestContextHolder.currentRequestAttributes().getAttribute("currentUser", RequestAttributes.SCOPE_SESSION);
		if(user!=null){
			return (User)user;
		}else{
		    return User.createInitalUser(); 
		}
    }
	
	/**
	 * Selects the home page and populates the model with a message
	 */
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Model model) {
		logger.info("Welcome home!");
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		 
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "home";
	}
	
	
	//setter and getter
	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}


	public ProductService getProductService() {
		return productService;
	}


	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

}
